const { DictModel } = require('../../models');

const DictService = {
  // 添加
  add: async data => {
    try {
      const result = await DictModel.create(data);
      if (result) {
        return {
          success: true,
          code: 1,
          msg: '新增成功',
        };
      } else {
        return {
          success: false,
          code: 1,
          msg: '新增失败',
        };
      }
    } catch (error) {
      return {
        success: false,
        code: 0,
        msg: '新增失败' + error,
        data: null,
      };
    }
  },
  // 删除
  delete: async _id => {
    try {
      if (!_id) {
        return {
          success: false,
          code: 0,
          msg: '删除失败:' + '_id不存在',
        };
      } else {
        const result = await DictModel.deleteOne({ _id });
        if (result) {
          return {
            success: true,
            code: 1,
            msg: '删除成功',
          };
        } else {
          return {
            success: false,
            code: 0,
            msg: '删除失败',
          };
        }
      }
    } catch (error) {
      return {
        success: false,
        code: 0,
        msg: '删除失败:' + error,
        data: null,
      };
    }
  },
  // 修改
  edit: async (_id, data) => {
    try {
      if (!_id) {
        return {
          success: false,
          code: 0,
          msg: '修改失败:' + '_id不存在',
          data: null,
        };
      } else {
        const result = await DictModel.findOneAndUpdate({ _id }, data);
        if (result) {
          return {
            success: true,
            code: 1,
            msg: '修改成功',
          };
        } else {
          return {
            success: false,
            code: 0,
            msg: '修改失败:' + 'name不存在',
            data: null,
          };
        }
      }
    } catch (error) {
      return {
        success: false,
        code: 0,
        msg: '修改失败:' + error,
        data: null,
      };
    }
  },
  // 查询所有
  list: async name => {
    try {
      const condition = {};
      if (name) {
        condition.name = name;
      }
      const result = await DictModel.find(condition, ['name', 'label', 'value', 'description']);
      if (result) {
        return {
          success: true,
          code: 1,
          msg: '查询成功',
          data: result,
        };
      } else {
        return {
          success: false,
          code: 0,
          msg: '查询失败',
          data: null,
        };
      }
    } catch (error) {
      return {
        success: false,
        code: 0,
        msg: '查询失败' + error,
        data: null,
      };
    }
  },
};

module.exports = DictService;
